<template>
	<view class="content">
		<mch_maekNo :mch="data.mch.title || ''" :markNo="data.markNo"></mch_maekNo>
		<!-- button 按钮式单选 -->
		<view class="remark" v-if="!data.id">
			<wd-radio-group v-model="remark" shape="button" class="radioG">
				<wd-radio value="堂食" checked-color="c32136">堂食</wd-radio>
				<wd-radio value="打包" checked-color="c32136">打包</wd-radio>
				<wd-radio v-if="useAddress" value="配送" checked-color="c32136">配送</wd-radio>
			</wd-radio-group>
		</view>

		<view class="list">
			<view class="item">
				<view class="title">
					<view class="shopname">菜品详情</view>
				</view>
				<view class="goods" v-if="data.id">
					<order_good_item v-for="(items, index) in data.item.ordersItemBOList" :key="index" :item="items"></order_good_item>
				</view>
				<view class="goods" v-else>
					<order_good_item v-for="(items, index) in data.cart_list" :key="index" :item="items"></order_good_item>
				</view>
				<view class="good_pay">共{{ data.item.goodsCount || data.goodCount }}件商品</view>
			</view>
		</view>
		<!-- 地址模块 -->
		<view v-if="useAddress && remark == '配送'" class="item" @click="data.id == '' ? onsel() : ''">配送地址：{{ address || '请选择' }}</view>
		<view v-if="useAddress && remark == '配送'" class="xz">配送须知：目前配送仅支持鹤壁市淇滨区内，请注意配送地址</view>
		<wd-popup v-model="addressShow" position="bottom" closeable>
			<Address @sel="Sel"></Address>
		</wd-popup>
		<view class="bottom" v-if="data.item.status === 'UNPAID' || !data.id">
			<view class="pays l">
				<text>合计：</text>
				{{ data.item.payAmount || data.goodPay }}元
			</view>
			<view class="btns r" v-if="data.isclick" @click="postpay">去支付</view>
			<view class="btns r" v-else>去支付</view>
		</view>
		<view class="footer" v-if="data.return_show">
			<view class="btn" @click="onpayshow">申请退款</view>
		</view>
	</view>
	<wd-action-sheet v-model="data.payshow" :actions="data.actions" @close="onClose" @select="onSelect" title="请选择支付方式" />
	<wd-popup v-model="data.show" position="bottom" @close="onClose" closeable>
		<view class="pop_title">售后退款</view>
		<view class="item">
			<view class="goods">
				<ret_item v-for="(items, index) in data.item.ordersItemBOList" :key="index" :item="items" :index="index" @bool="oncheckbox" @count="change"></ret_item>
			</view>
		</view>
		<view class="good_remark">
			<textarea v-model="data.remark" placeholder="请说明退款原因" />
		</view>
		<view class="btn" @click="onreturn">立即退款</view>
	</wd-popup>
</template>

<script lang="ts" setup>
import Address from '@/components/address/address.vue';
import { reactive, ref } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { err, toast, get } from '@/utils/uniapi';
import { api } from '@/api/store_api';
import { sum } from '@/utils/utils';
const remark = ref<string>('堂食');
const addressShow = ref<boolean>(false);
const address = ref<string>('');
const data = reactive({
	id: '',
	item: { ordersItemBOList: [], goodsCount: '', status: '', payAmount: '', deskId: '' },
	actions: [
		{
			name: '微信支付',
			payType: 'WX_PAY'
		},
		{
			name: '积分支付',
			payType: 'INTEGRAL_PAY'
		}
	],
	payshow: false,
	isclick: true,
	show: false,
	remark: '',
	return_show: false,
	mch: get('mch'),
	markNo: get('markNo'),
	cart_list: [],
	goodCount: 0,
	goodPay: 0
});
const cid = ref<string>('');
const useAddress = ref<boolean>(use());
onLoad((e: any) => {
	if (e.id) {
		data.id = e.id;
		dtlorder();
	} else {
		cartList();
	}
});
function use() {
	const arr = get('mchuse');
	let bool: any;
	arr.forEach((e: any) => {
		if (e.feature == '收货地址') {
			bool = e.enable;
		}
	});
	return bool;
}
function onsel() {
	console.log(1);
	addressShow.value = true;
}
function Sel(e: any) {
	console.log(e);
	addressShow.value = e.show;
	address.value = e.address;
}
async function cartList() {
	try {
		const deskId = get('deskId');
		const res = await api.cartList({ deskId });
		if (res.respCode === 200) {
			const cart_list = JSON.parse(res.source);
			console.log(cart_list);
			data.cart_list = cart_list;
			const { sum_count, sum_price } = sum(cart_list);
			data.goodCount = sum_count;
			data.goodPay = sum_price;
		}
	} catch (e) {
		err(e);
	}
}
async function dtlorder() {
	try {
		const { id } = data;
		const { respCode, source } = await api.chaorders({ id });
		if (respCode === 200) {
			let item = JSON.parse(source);
			item.ordersItemBOList.forEach((e: any) => {
				e.checkbox = false;
				e.returncount = 1;
			});
			address.value = item.address;
			remark.value = item.remark;
			const { status, returnCount, returnAmount } = item;
			if (status === 'SUCCESS' && returnCount === 0 && returnAmount === 0) {
				data.return_show = true;
			}
			data.item = item;
		}
	} catch (error) {
		err(error);
		throw error;
	}
}
function onpayshow() {
	data.show = true;
}
async function postpay() {
	const tmplIds = ['0LEdamd0lkPiv8NspXo-XgVSXOea4ALd37ysI1RBlzM'];
	wx.requestSubscribeMessage({
		tmplIds,
		success(res) {
			console.log(res);
		},
		fail(err) {
			console.log(err);
		}
	});
	if (!data.id) {
		try {
			uni.showLoading({ title: '加载中' });
			const { cart_list } = data;
			const deskId = get('deskId');
			const cartIdList = cart_list.map((e: any) => e.id);
			const res = await api.orders({ cartIdList, deskId, remark: remark.value, address: address.value });
			if (res.respCode === 200) {
				const ids = JSON.parse(res.source).id;
				cid.value = ids;
				data.id = ids;
				dtlorder();
				uni.showLoading({});
			} else {
				toast(res.msg);
			}
		} catch (e) {
			err(e);
		}
	}
	data.payshow = true;
}
function onClose() {
	data.show = false;
	data.payshow = false;
}
async function onSelect(e: any) {
	const { payType } = e.item;
	const { isclick, id } = data;
	if (!isclick) return;
	data.isclick = false;
	uni.showLoading({ title: '支付中' });
	try {
		const memberId = get('user').id;
		const datas = { ordersId: id || cid.value, payType, memberId };
		const { respCode, msg, source } = await api.userpay(datas);
		if (respCode === 200) {
			if (payType === 'WX_PAY') {
				const payment = JSON.parse(source);
				payment.timeStamp = payment.timeStamp.toString();
				try {
					await new Promise((resolve, reject) => {
						wx.requestPayment({
							...payment,
							success: (res: any) => {
								resolve(res);
							},
							fail: (err: any) => {
								reject(err);
								canpay(id || cid.value);
							}
						});
					});
					paytoast();
				} catch (error) {
					err(error);
				}
			} else {
				paytoast();
			}
		} else {
			toast(msg);
		}
	} catch (error) {
		err(error);
		toast('发起支付请求失败，请稍后再试！');
		throw error;
	} finally {
		uni.hideLoading();
		data.isclick = true;
	}
}
async function canpay(ordersId: string) {
	uni.showLoading({ title: '取消支付中' });
	try {
		const res = await api.cnacelpay({ ordersId });
		if (res.respCode === 200) {
			toast('取消支付成功');
		} else {
			toast(res.msg);
		}
	} catch (e) {
		err(e);
	}
}
function paytoast() {
	toast('支付成功，即将返回订单列表');
	setTimeout(() => {
		uni.reLaunch({
			url: '/pages/order/order'
		});
	}, 1500);
}
function oncheckbox(e: any) {
	const { items, index } = e;
	const { item } = data;
	item.ordersItemBOList[index] = items;
	data.item = item;
}
function change(e: any) {
	const { items, index } = e;
	const { item } = data;
	item.ordersItemBOList[index] = items;
	data.item = item;
}
async function onreturn() {
	try {
		const ordersReturnItemBOList = data.item.ordersItemBOList.filter((e: any) => e.checkbox).map((e: any) => ({ id: e.id, goodsCount: e.returncount }));
		if (ordersReturnItemBOList.length === 0) {
			toast('请选择需要退款的商品');
		} else {
			const datas = {
				orderId: data.id,
				ordersReturnItemBOList,
				deskId: data.item.deskId,
				remark: data.remark
			};
			const res = await api.payrefund(datas);
			if (res.respCode === 200) {
				toast('发起退款成功，等待商家确认');
				data.show = false;
				dtlorder();
			} else {
				toast(res.msg);
			}
		}
	} catch (error) {
		err(error);
		throw error;
	}
}
</script>

<style scoped lang="scss">
.remark {
	width: 710rpx;
	margin: 20rpx auto;
	background-color: #fff;
	height: 100rpx;
	display: flex;
	align-items: center;
}
wd-radio-group {
	height: 100rpx;
}
.list {
	width: 100%;
}
.item {
	width: 710rpx;
	background: #ffffff;
	border-radius: 24rpx 24rpx 24rpx 24rpx;
	opacity: 1;
	margin: 24rpx auto;
	padding: 16rpx 24rpx;
	box-sizing: border-box;
}
.xz {
	width: 710rpx;
	background: #ffffff;
	border-radius: 24rpx;
	margin: 24rpx auto;
	padding: 16rpx 24rpx;
	box-sizing: border-box;
	font-size: 24rpx;
}
.title {
	width: 656rpx;
	overflow: hidden;
	padding-bottom: 8rpx;
	border-bottom: 4rpx dashed #ebebf0;
	margin: 0 auto;
}
.shopname {
	font-size: 24rpx;
	font-family: Inter-Regular, Inter;
	font-weight: 400;
	color: #28282b;
	white-space: nowrap;
	text-overflow: ellipsis;
	overflow: hidden;
}
.stats {
	font-size: 28rpx;
	font-family: Inter-Regular, Inter;
	font-weight: 400;
}
.goods {
	width: 656rpx;
	margin: 0 auto;
	border-bottom: 4rpx dashed #ebebf0;
	padding-bottom: 12rpx;
}

.good_pay {
	text-align: right;
	font-size: 24rpx;
	font-family: Source Han Sans CN-Regular, Source Han Sans CN;
	font-weight: 400;
	color: rgba(0, 0, 0, 0.6);
	margin-top: 26rpx;
	margin-right: 12rpx;
}
.radio {
	width: 710rpx;
	margin: 0 auto;
}
.btn {
	width: 652rpx;
	height: 80rpx;
	background: #c32136;
	border-radius: 56rpx 56rpx 56rpx 56rpx;
	margin: 0 auto;
	font-size: 32rpx;
	font-family: Source Han Sans CN-Medium, Source Han Sans CN;
	font-weight: 600;
	color: #ffffff;
	text-align: center;
	line-height: 80rpx;
}
.van-cell {
	margin-bottom: 20rpx;
}
.pop_title {
	width: 710rpx;
	text-align: center;
	font-size: 36rpx;
	font-weight: bold;
	padding-bottom: 10rpx;
	border-bottom: 2rpx solid #000;
	margin: 0 auto;
	margin-top: 20rpx;
}
.stepper_img {
	width: 40rpx;
	height: 40rpx;
	border: none;
	background-color: transparent;
}
.good_remark {
	width: 710rpx;
	min-height: 168rpx;
	background: #ffffff;
	border-radius: 24rpx;
	margin: 10rpx auto;
	box-sizing: border-box;
}
.good_remark textarea {
	width: 100%;
	height: 100rpx;
}
.bottom {
	background-color: #4c4b4b;
	width: 670rpx;
	height: 80rpx;
	position: fixed;
	bottom: 96rpx;
	left: 50%;
	transform: translate(-50%);
	border-radius: 30rpx;
}
.bottom .pays {
	font-size: 36rpx;
	font-weight: 500;
	color: #ffffff;
	line-height: 80rpx;
	margin-left: 16rpx;
}
.bottom .pays text {
	font-size: 24rpx;
	font-weight: 500;
	color: #ffffff;
}
.bottom .btns {
	background-color: #c32136;
	width: 203rpx;
	height: 80rpx;
	border-radius: 30rpx;
	font-size: 32rpx;
	font-weight: 500;
	color: #ffffff;
	text-align: center;
	line-height: 80rpx;
}
</style>
